import {coreApi} from '../apis/core-util'
import TimeStore from 'lib/stores/time-store'
import _ from 'underscore'
import moment from 'moment'

export default class PieChart {
  constructor(props, container) {
    this.container = container;
    this.$state = {
      pieChart: {
        loading: true
      },

      currentPieType: 'model',
      pieListDataSource: [
        {label: '设备分布', value: 'model'},
        {label: 'App 版本', value: 'appversion'},
        {label: '操作系统版本', value: 'osversion'}
      ],

      pieChartSettings: {
        legend: {
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'middle',
          x: -50,
          navigation: {
            animation: true
          }
        },
        plotOptions: {
          pie: {
            dataLabels: {
              enabled: false
            },
            showInLegend: true
          }
        }
      }
    };

    this.pieChartApi = coreApi({
      size: 1,
      offset: 0,
      limit: 5,
      sm: 1,
      classify: () => this.$state.currentPieType,
      urlName: 'activitytracesimilar'
    }, TimeStore.getValue);

    this.$state.pieChartFormatter = function(tooltip) {
      let template = '<span style="color: <%= point.color %>">从 <%= begin %> - <%= end %></span><br/>' +
                     '<b>最小流畅度：</b><%= point.customData.y.fmtVal %><br/>' +
                     '<b>卡顿次数：</b><%= point.customData.z.fmtVal %>';
      return _.template(template)({
        point: this.point,
        begin: moment(this.point.customData.startTime).format('YYYY-MM-DD HH:mm'),
        end: moment(this.point.customData.endTime).format('YYYY-MM-DD HH:mm')
      });
    };
  }

  $change_pie_type(payload) {
    this.$state.currentPieType = payload.pieType;
    this.container.emit();
  }

  $load() {
    return this.pieChartApi.fetch().done((json, params) => {
      this.$state.pieChart = {
        data: this.parseToChart(json)
      };
      this.container.emit();
    }).fail((err) => {
      this.$state.pieChart = {
        error: err
      };
      this.container.emit();
    });
  }

  parseToChart(json) {
    let result = {
      series: _.chain(json.result).map((item,n) => {
        return {
          id: item.key.id,
          name: item.key.name,
          data: _.chain(item.data).map((p) => {
            return {
              x: p.st,
              y: p.count,
              customData: {
                startTime: p.st,
                endTime: p.et,
                y: {
                  fmtVal: p.sm,
                  label: '最小流畅度'
                },
                z: {
                  fmtVal: p.count,
                  label: '卡顿次数'
                }
              }
            };
          }).value()
        }
      }).value()
    }; // end result

    return result;
  } // end parseToChart

  $change_device_type(payload) {
    this.$state.currentPieType = payload.deviceType;
    this.$load();
  }
}
